<template>
  <Modal v-model="modal"  fullscreen class="bind-modal">
    <div slot="header">
      <p class="tc">商品绑定<span class="font-red">（只能单选）</span></p>
    </div>
    <div class="container-header large">
      <Form class="search">
        <Row>
          <Col span="10">
            <FormItem label="商品编码">
              <Input v-model.trim="list.form.code" placeholder="商品编码" :maxlength="20" @on-enter="onSearchBtnClick"/>
            </FormItem>
            <FormItem label="商品名称">
              <Input v-model.trim="list.form.keyword" placeholder="商品名称，品牌，分类，子标题" :maxlength="100" @on-enter="onSearchBtnClick"/>
            </FormItem>
          </Col>
          <Col span="10">
            <FormItem label="商品类目">
              <CategorySelect v-model="list.form.categoryId"></CategorySelect>
            </FormItem>
            <FormItem label="商品品牌" placeholder="商品品牌">
              <BrandSelect v-model="list.form.brandId" @input="onSearchBtnClick"></BrandSelect>
            </FormItem>
          </Col>
          <Col class-name="search" span="2">
            <Button class="btn-search large" type="primary" icon="ios-search" @click="onSearchBtnClick"></Button>
          </Col>
        </Row>
      </Form>
    </div>
    <Table
      ref="table"
      :height="options.tableHeight"
      stripe
      :columns="list.columns"
      :data="list.data"
      no-data-text="亲，没有找到相关记录哦！~"></Table>
    <div class="pager">
      <Page 
      :total="list.totalItem" 
      :current="list.currentPage"
      :page-size="list.pageSize"
      @on-change="onPageChange"
      @on-page-size-change="onPageSizeChange"
      show-sizer 
      placement="top"></Page>
    </div>
    <Loader :status="status" @refresh="getData"></Loader>
    <div slot="footer">
      <Button class="mr" size="large" @click="modal = false">取消</Button>
      <Button type="primary" :disabled="disabled" size="large" @click="onPreBind">确定</Button>
    </div>
  </Modal>
</template>
<script>
import CategorySelect from '@/components/CategorySelect'
import BrandSelect from '@/components/BrandSelect'
import list from './BindEditData'
import { clearEmpty } from '@/util'
export default {
  components: {
    CategorySelect,
    BrandSelect
  },
  data () {
    return {
      id: '',
      modal: false,
      disabled: false,
      list: list,
      status: 'pass',
      options: {
        tableHeight: 300
      },
      materialIds: [],
      selection: []
    }
  },
  mounted() {
    this.$bus.$on('onRadio', ({index, row}) => this.onRadio(index, row))
  },
  destroyed() {
    this.$bus.$off()
  },
  methods: {
    onSearchBtnClick() {
			this.list.currentPage = 1
			this.getData()
		},
    updateForm(materialIds) {
      this.initTable()
      this.modal = false
      this.disabled = false
      this.list.currentPage = 1
      this.selection = []
      this.materialIds = materialIds
      this.openModal()
      this.getData()
    },
    openModal() {
      this.modal = true
    },
    closeModal() {
      this.modal = false
    },
    getData() {
      this.status = 'loading'
      this.selection = []
      let param = {
        query: {},
        current: this.list.currentPage,
        size: this.list.pageSize,
        code: this.list.form.code,
        keyword: this.list.form.keyword,
        categoryId: this.list.form.categoryId,
        brandId: this.list.form.brandId
      }
      param = clearEmpty(param)
      this.$jsonPost("/product/erp_materiel/product/page", param).then(data => {
        this.list.data = []
        this.list.totalItem = Number(data.total)
        this.list.data = (data.records || []).map(item => {
          return {
            ...item,
            brandName: item.brandName,
            categoryName: item.categoryName,
            centerProductId: item.centerProductId,
            code: item.code,
            isShelf: item.isShelf,
            ownerName: item.ownerName,
            title: item.title,
            unit: item.unit,
            isShow: false
          }
        })
        this.status = "pass"
      }).catch(() => {
        this.status = "error"
      })
    },
    onRadio(index, row) {
      this.list.data[index] = row
      this.selection = [row]
      this.list.data.filter((item, inx) => inx !== index).map(m => {
        m.isShow = false
      })
    },
    onPageChange(number) {
      this.selection = []
			this.list.currentPage = number
      this.getData()
		},
    onPageSizeChange(pageSize) {
      this.selection = []
			this.list.currentPage = 1
			this.list.pageSize = pageSize
			this.getData()
    },
    onPreBind() {
      if (this.status === 'loading' || this.disabled) return
      if (this.selection.length === 0) {
        this.$Notice.warning({
          title: '请先选择要绑定的商品'
        })
        return
      }
      if (this.selection.length > 1) {
        this.$Notice.warning({
          title: '只能选择一个商品'
        })
        return
      }
      this.$jsonPost(`/product/erp_materiel/pre_binding/${this.selection[0].centerProductId}`, this.materialIds).then(data =>{
        if (data[0].resultMessage) {
          this.$Modal.confirm({
            title: '提示',
            content: `${data[0].resultMessage},还要继续绑定吗？`,
            onOk: () => {
              this.onSave()
            },
            onCancel: () => {
              this.disabled = false
            }
          })
        } else {
          this.onSave()
        }
      })
    },
    onSave() {
      this.disabled = true
      this.$jsonPost(`/product/erp_materiel/binding/${this.selection[0].centerProductId}`, this.materialIds).then(data =>{
        this.$emit('complete')
        this.closeModal()
        this.$Notice.success({
          title: '绑定成功'
        })
      }).catch(() => {
        this.$Notice.error({
          title: '绑定失败'
        })
        this.disabled = false
      })
    },
    initTable(translate = 0) {
      this.setTableSize(translate)
      window.addEventListener('resize', () => {
        this.tableTimer && clearTimeout(this.tableTimer)
        this.tableTimer = setTimeout(() => this.setTableSize(translate), 100)
      })
    },
    setTableSize(translate = 0) {
      let target = document.documentElement.clientHeight || document.body.clientHeight
      if (!target) return
      let height = target - 240 - translate
      this.options.tableHeight = height
    }
  }
}
</script>